package com.csw.springbootquartz.task.runstop;

import com.csw.springbootquartz.entity.SchedulerJobEntity;
import com.csw.springbootquartz.service.SchedulerJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;

@Service
@Slf4j
/*
【cron】
#表达式生成网站
https://www.pppet.net/
指定日时，周 需设置为不指定
指定周时，日 需设置为不指定
年份为不指定，星期需大写
#解析成中文
https://51tools.info/cron/
*/

public class ControllerTask {

    private static final ThreadPoolTaskScheduler THREAD_POOL_TASK_SCHEDULER = new ThreadPoolTaskScheduler();

//    private static SchedulerJobService schedulerJobService;
//
//    public ControllerTask2(SchedulerJobService schedulerJobService) {
//        ControllerTask2.schedulerJobService = schedulerJobService;
//    }

    @Autowired
    private SchedulerJobService schedulerJobService;

    public static void stopJob() {
        log.error("打断当前b任务");
        THREAD_POOL_TASK_SCHEDULER.destroy();
    }

    @PostConstruct
    public void run() {
        ControllerTask.stopJob();
        THREAD_POOL_TASK_SCHEDULER.initialize();
        SchedulerJobEntity schedulerJobEntity = schedulerJobService.findByid("222");
        log.error("进入定时任务{}", schedulerJobEntity);
        String running = schedulerJobEntity.getRunning();
        Runnable runnable = () -> {
            if ("on".equals(running)) {
                log.error("ControllerTask*********************************{},{}", System.currentTimeMillis(), LocalDateTime.now());
            }
        };
        // 0 0 0 0 0 7
        // 0/5 * * * * *
        THREAD_POOL_TASK_SCHEDULER.schedule(runnable, new CronTrigger(schedulerJobEntity.getCron()));
    }

}
